<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
    <h1>这是index文件</h1>
    <input type="text" placeholder="用户名称"/>
    <button class="conncet">连接</button>
    <textarea name="" id="" cols="30" rows="10"></textarea>
    <button class="to">发送</button>
    <script>
        var conncetion = null;
        $(".conncet").click(function () {
            var user = $("input").val();
            if (conncetion) return;
            // 建立連接
            // 获取一个连接对象
            conncetion = new WebSocket("ws://localhost:3000/" + user);
            conncetion.onopen = function () {
                console.log("连接成功");
            }
            conncetion.onclose = function () {
                console.log("连接失败");
            }

            conncetion.onmessage = function (res) {
                var obj = JSON.parse(res.data);
                console.log(obj);
            }

        })

        $(".to").click(function () {
            var text = $("textarea").val();
            if (!condition) {
                alert("没有连接")
                return;
            };
            var obj = { data: text };
            conncetion.send(JSON.stringify(obj));

            
        })
    </script>
</body>

</html>